package com.gzhryc.shared_device.oem.h5.mng.controllers.agent;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import com.gzhryc.common.StringTools;
import com.gzhryc.common.data.dto.AjaxResult;
import com.gzhryc.common.data.dto.ListResult;
import com.gzhryc.common.data.dto.SelectResult;
import com.gzhryc.common.exceptions.LogicException;
import com.gzhryc.servlet.DtoConstants;
import com.gzhryc.servlet.WebUtils;
import com.gzhryc.servlet.annotation.Route;
import com.gzhryc.shared_device.oem.code.ConfigUtils;
import com.gzhryc.shared_device.oem.code.agent.dao.db.AgentLevel;
import com.gzhryc.shared_device.oem.code.agent.dao.db.AgentLevelFuncModel;
import com.gzhryc.shared_device.oem.code.agent.dao.enums.AgentLevelFuncModelEnum;
import com.gzhryc.shared_device.oem.code.agent.services.AgentLevelFuncModelService;
import com.gzhryc.shared_device.oem.code.agent.services.AgentLevelService;
import com.gzhryc.shared_device.oem.code.agent.services.AgentService;
import com.gzhryc.shared_device.oem.code.agent.services.dto.AgentLevelSearch;
import com.gzhryc.shared_device.oem.code.config.BusinessConfig;
import com.gzhryc.shared_device.oem.code.config.dao.db.FuncModel;
import com.gzhryc.shared_device.oem.code.config.dao.enums.FuncModelEnum;
import com.gzhryc.shared_device.oem.code.config.services.FuncModelService;
import com.gzhryc.shared_device.oem.code.config.services.dto.FuncModelSearch;
import com.gzhryc.shared_device.oem.code.user.ERoleType;
import com.gzhryc.shared_device.oem.h5.mng.WebConstants;

public class AgentLevelController {

    @Route(value = { "/agent/level/list.html" })
    public String list(HttpServletRequest request) {
        return "/agent/level/list.html";
    }

    @Route(value = "/agent/level/list.data")
    public ListResult<AgentLevel> listData(HttpServletRequest request) {
        ListResult<AgentLevel> result = new ListResult<>(DtoConstants.NULL_DATA, "暂无数据");
        AgentLevelSearch search = new AgentLevelSearch();
        result.getBody().setData(AgentLevelService.self().findBySearch(search));
        if (result.getBody().getData() != null) {
            result.setCode(DtoConstants.SUCCESS,null);
        }
        return result;
    }

    @Route(value = { "/agent/level/add.html" })
    public String add(HttpServletRequest request) {
        Integer num = AgentLevelService.self().getByMaxNum() + 1;
        request.setAttribute("num",num);
        BusinessConfig config = ConfigUtils.getBusinessConfig();
    	request.setAttribute("serviceChargeRatio", config.getServiceChargeRatio());
        return "/agent/level/edit.html";
    }

    @Route(value = { "/agent/level/add.do" })
    public AjaxResult doAdd(HttpServletRequest request) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR,"新增失败，请稍后再试");
        AgentLevel agentLevel = WebUtils.getParameter(request, AgentLevel.class);
        try {
        	if(agentLevel.getServiceChargeRatio() == null || agentLevel.getServiceChargeRatio() < 0 || agentLevel.getServiceChargeRatio() >= 100) {
                throw new LogicException("请输入正确的平台服务费分成百分比");
            }
            if(AgentLevelService.self().add(agentLevel,false)){
                result.setCode(DtoConstants.SUCCESS,null);
            }
        } catch (LogicException e) {
            result.setMsg(e.getMessage());
        }
        return result;
    }

    @Route(value = { "/agent/level/info.html" })
    public String update(HttpServletRequest request) {
        Integer num = WebUtils.getInteger(request,"num");
        if(num != null){
            AgentLevel agentType = AgentLevelService.self().getByNum(num);
            WebUtils.setAttribute(request,agentType);
        }
        return "/agent/level/info.html";
    }

    @Route(value = { "/agent/level/update.do" })
    public AjaxResult doUpdate(HttpServletRequest request) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR,"修改失败，请稍后再试");
        AgentLevel agentLevel = WebUtils.getParameter(request, AgentLevel.class);
        try {
        	if(agentLevel.getServiceChargeRatio() == null || agentLevel.getServiceChargeRatio() < 0 || agentLevel.getServiceChargeRatio() >= 100) {
                throw new LogicException("请输入正确的平台服务费分成百分比");
            }
            if(AgentLevelService.self().updateNotNull(agentLevel)){
                result.setCode(DtoConstants.SUCCESS,null);
            }
        } catch (LogicException e) {
            result.setMsg(e.getMessage());
        }
        return result;
    }

    @Route(value = { "/agent/level/jump/add.html" })
    public String jumpAdd(HttpServletRequest request) {
    	BusinessConfig config = ConfigUtils.getBusinessConfig();
    	request.setAttribute("serviceChargeRatio", config.getServiceChargeRatio());
        return "/agent/level/edit.html";
    }

    @Route(value = { "/agent/level/jump/add.do" })
    public AjaxResult doJumpAdd(HttpServletRequest request) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR,"新增失败，请稍后再试");
        AgentLevel agentLevel = WebUtils.getParameter(request, AgentLevel.class);
        try {
        	if(agentLevel.getServiceChargeRatio() == null || agentLevel.getServiceChargeRatio() < 0 || agentLevel.getServiceChargeRatio() >= 100) {
                throw new LogicException("请输入正确的平台服务费分成百分比");
            }
            if(AgentLevelService.self().add(agentLevel,true)){
                result.setCode(DtoConstants.SUCCESS,null);
            }
        } catch (LogicException e) {
            result.setMsg(e.getMessage());
        }
        return result;
    }

    @Route(value = { "/agent/level/del.do" })
    public AjaxResult doDel(HttpServletRequest request) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR,"删除失败，请稍后再试");
        Integer num = WebUtils.getInteger(request,"num");
        try {
            if(AgentLevelService.self().deleteByNum(num)){
                result.setCode(DtoConstants.SUCCESS,null);
            }
        } catch (LogicException e) {
            result.setMsg(e.getMessage());
        }
        return result;
    }

    @Route(value = "/agent/level/func_model/list.data")
    public ListResult<AgentLevelFuncModel> funcModelListData(HttpServletRequest request) {
        ListResult<AgentLevelFuncModel> result = new ListResult<>(DtoConstants.NULL_DATA, "暂无数据");
        Integer level = WebUtils.getInteger(request,"level");
        List<AgentLevelFuncModel> data = AgentLevelFuncModelService.self().findJoinByLevel(level);
        if(data != null && data.size() > 0){
        	String resDomain = WebConstants.getResDomain(request);
            for(AgentLevelFuncModel item : data){
                if(StringTools.isNotBlank(item.getFuncModel().getIconUrl())){
                    item.getFuncModel().setIconUrl(resDomain + item.getFuncModel().getIconUrl());
                }
            }
            result.setCode(DtoConstants.SUCCESS, null);
            result.getBody().setData(data);
        }
        return result;
    }

    @Route(value = { "/agent/level/func_model/add.html" })
    public String addFuncModel(HttpServletRequest request) {
        request.setAttribute("type", ERoleType.Agent.index());
        request.setAttribute("stateList", AgentLevelFuncModelEnum.State.values());
        return "/agent/level/func_model/edit.html";
    }

    @Route(value = { "/agent/level/func_model/add.do" })
    public AjaxResult doAddFuncModel(HttpServletRequest request) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR,"新增失败，请稍后再试");
        AgentLevelFuncModel agentLevelFuncModel = WebUtils.getParameter(request, AgentLevelFuncModel.class);
        try {
            if(AgentLevelFuncModelService.self().add(agentLevelFuncModel)){
                result.setCode(DtoConstants.SUCCESS,null);
            }
        } catch (LogicException e) {
            result.setMsg(e.getMessage());
        }
        return result;
    }

    @Route(value = { "/agent/level/func_model/del.do" })
    public AjaxResult doDelFuncModel(HttpServletRequest request) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR,"删除失败，请稍后再试");
        Integer level = WebUtils.getInteger(request,"level");
        Long funcModelId = WebUtils.getLong(request,"funcModelId");
        try {
            if(AgentLevelFuncModelService.self().deleteByKeys(level,funcModelId)){
                result.setCode(DtoConstants.SUCCESS,null);
            }
        } catch (LogicException e) {
            result.setMsg(e.getMessage());
        }
        return result;
    }

    @Route("/agent/level/func_model/select.data")
    public SelectResult selectData(HttpServletRequest request) {
        SelectResult result = new SelectResult(DtoConstants.SUCCESS);
        String term = request.getParameter("term");
        Integer type = WebUtils.getInteger(request,"type");
        Integer level = WebUtils.getInteger(request,"level");
        Integer state = WebUtils.getInteger(request,"state",FuncModelEnum.State.Choose.index());
        Integer page = WebUtils.getInteger(request, "page", 1);

        FuncModelSearch search = new FuncModelSearch();
        search.setName(term);
        search.setType(type);
        if(state != 0) {
            search.setState(state);
        }
        Long total = 0L;
        List<FuncModel> list = FuncModelService.self().findBySearch(search, page, WebConstants.PAGE_LIMIT);
        if (list != null) {
            List<AgentLevelFuncModel> levelFuncModelList = null;
            if(level != null){
                levelFuncModelList = AgentLevelFuncModelService.self().findJoinByLevel(level);
            }

            for (FuncModel funcModel : list) {
                boolean flag = true;
                if(levelFuncModelList != null && levelFuncModelList.size() > 0){
                    for(AgentLevelFuncModel levelFuncModel : levelFuncModelList){
                        if(levelFuncModel.getFuncModelId().equals(funcModel.getId())){
                            flag = false;
                            break;
                        }
                    }
                }
                if(flag) {
                    SelectResult.Item item = new SelectResult.Item();
                    item.setId(funcModel.getId().toString());
                    item.setText(funcModel.getName() + " - " + funcModel.getStateName());
                    result.getBody().getData().add(item);
                }
            }
            total += list.size();
        }
        result.getBody().setPage(page);
        result.getBody().setLimit(WebConstants.PAGE_LIMIT);
        result.getBody().setTotal(total);
        return result;
    }

    @Route(value = { "/agent/level/service_charge_ratio/refresh.html" })
    public String refreshServiceChargeRatio(HttpServletRequest request) {
    	 Integer num = WebUtils.getInteger(request,"num");
         if(num != null){
             AgentLevel agentLevel = AgentLevelService.self().getByNum(num);
             WebUtils.setAttribute(request,agentLevel);
         }
        return "/agent/level/service_charge_ratio/refresh.html";
    }
    
    @Route(value = { "/agent/level/service_charge_ratio/refresh.do" })
    public AjaxResult doRefreshServiceChargeRatio(HttpServletRequest request) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR,"刷新失败，请稍后再试");
        Integer num = WebUtils.getInteger(request,"num");
        Integer type = WebUtils.getInteger(request,"type");
        if(num != null && type != null){
            AgentLevel agentLevel = AgentLevelService.self().getByNum(num);
            if(agentLevel != null) {
            	try {
	            	if(type == 1) {
	            		//刷新成同一个
	            		if(AgentService.self().updateServiceChargeRatioByLevel(agentLevel.getNum(), agentLevel.getServiceChargeRatio())) {
	            			result.setCode(DtoConstants.SUCCESS, null);
	            		}
	            	}else if(type == 2) {
	            		//刷新大于当前
	            		if(AgentService.self().updateServiceChargeRatioByLevel2(agentLevel.getNum(), agentLevel.getServiceChargeRatio())) {
	            			result.setCode(DtoConstants.SUCCESS, null);
	            		}
	            	}else if(type == 3) {
	            		//刷新小于当前
	            		if(AgentService.self().updateServiceChargeRatioByLevel3(agentLevel.getNum(), agentLevel.getServiceChargeRatio())) {
	            			result.setCode(DtoConstants.SUCCESS, null);
	            		}
	            	}
            	}catch(LogicException e) {
            		result.setMsg(e.getMessage());
            	}
            }
        }
        return result;
    }

}
